package main

import (
	"AttackTracer/Analyzer/ML"
	"AttackTracer/Analyzer/RPC"
	"AttackTracer/Analyzer/config"
	"AttackTracer/Analyzer/resourseMonitor"
	"fmt"
	"os"
)

var (
	Conf         config.Config
	IncidentChan = make(chan RPC.Incident, 10)
	PacketChan   = make(chan ML.PacketInfo, 10)
)

func init() {
	// get config file path from command line
	var configPath string
	if len(os.Args) != 2 {
		fmt.Println("no config file provided")
		configPath = "/etc/AttackTracer/analyzer.yaml"
	} else {
		configPath = os.Args[1]
	}
	fmt.Println("reading config from " + configPath)

	// parse config
	Conf, err := Conf.Parse(configPath)
	if err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}

	if err = Conf.Validate(); err != nil {
		fmt.Println(err.Error())
		os.Exit(1)
	}
	//log.Print(Conf)
}

func main() {
	fmt.Println("Analyzer starting")
	go RPC.ConnectTracingEngine(Conf.RpcConf, IncidentChan)

	// Incident Report test
	//IncidentChann <- RPC.Incident{
	//	Name:  "SayHello",
	//	Value: nil,
	//}

	go resourseMonitor.MonitorResourse()
	go ML.ConnectMLServer(Conf.MachineLearningConf, PacketChan)

	// TODO: this is a test, delete later
	testDuration := make([]int, 0, 1)
	testDuration = append(testDuration, 0)
	testPacket := ML.PacketInfo{
		Duration:               testDuration,
		ProtocolType:           "tcp",
		Service:                "http",
		Flag:                   "SF",
		SrcBytes:               181,
		DstBytes:               5450,
		Land:                   0,
		WrongFragment:          0,
		Urgent:                 0,
		Ho:                     0,
		NumFailedLogins:        0,
		LoggedIn:               1,
		NumCompromised:         0,
		RootShell:              0,
		SuAttempted:            0,
		NumRoot:                0,
		NumFileCreations:       0,
		NumShells:              0,
		NumAccessFiles:         0,
		NumOutboundCmds:        0,
		IsHostLogin:            0,
		IsGuestLogin:           0,
		Count:                  8,
		SrvCount:               8,
		SerrorRate:             0.0,
		SrvSerrorRate:          0.0,
		RerrorRate:             0.0,
		SrvRerrorRate:          0.0,
		SameSrvRate:            1.0,
		DiffSrvRate:            0.0,
		SrvDiffHostRate:        0.0,
		DstHostCount:           9,
		DstHostSrvCount:        9,
		DstHostSameSrvRate:     1.0,
		DstHostDiffSrvRate:     0.0,
		DstHostSameSrcPortRate: 0.11,
		DstHostSrvDiffHostRate: 0.0,
		DstHostSerrorRate:      0.0,
		DstHostSrvSerrorRate:   0.0,
		DstHostRerrorRate:      0.0,
		DstHostSrvRerrorRate:   0.0,
		Class:                  "normal.",
	}
	PacketChan <- testPacket

	RPC.Serve(Conf.RpcConf)
}
